<?php

/*============================================
Classe Userpartition
============================================*/

class Userpartition extends ModelObject{

	protected static $cached_object_list= array();
	protected $id_user;
	protected $id_partition;

	protected function __construct( $id_user,$id_partition){
		try{
			
			$this->id_user = $id_user;
			$this->id_partition = $id_partition;
		}
		catch(Excpetion $e){
			throw new Exception("La construction de l'objet de type get_class($this) a échouée",0,$e);
		}
	}

	public function getUser(){
		return User::get($this->id_user);
	}

	public function getPartition(){
		return Partition::get($this->id_partition);
	}

	public function setUser( $user){
		try{
			$temp = $this->id_user;
			if(is_null($user)){
				throw new Exception("Le paramètre \$user de type get_class($user) est null alors que la colonne dans la base est marquée comme NOT NULL");
			}
			else if(!($user instanceof User) || is_null($user->getId())){
				throw new Exception("Le paramètre \$user de type get_class($user) n'est pas du bon type ou n'est pas présent dans la base");
			}
			else {
				if($this->id_user !== $user->getId()){
					$this->id_user = $user->getId();
					$this->update();
				}
			}
		}
		catch(Exception $e){
			$this->id_user = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setUser() a échouée",0,$e);
		}
	}

	public function setPartition( $partition){
		try{
			$temp = $this->id_partition;
			if(is_null($partition)){
				throw new Exception("Le paramètre \$partition de type get_class($partition) est null alors que la colonne dans la base est marquée comme NOT NULL");
			}
			else if(!($partition instanceof Partition) || is_null($partition->getId())){
				throw new Exception("Le paramètre \$partition de type get_class($partition) n'est pas du bon type ou n'est pas présent dans la base");
			}
			else {
				if($this->id_partition !== $partition->getId()){
					$this->id_partition = $partition->getId();
					$this->update();
				}
			}
		}
		catch(Exception $e){
			$this->id_partition = $temp;
			throw new Exception("La modification de l'attribut par l'appel à la méthode setPartition() a échouée",0,$e);
		}
	}

	public static function create( $user,$partition){
		try{
			if (!is_null($user)){
				$id_user = $user->getId();
			}
			else{
				$id_user = null;
			}
			if (!is_null($partition)){
				$id_partition = $partition->getId();
			}
			else{
				$id_partition = null;
			}
			$userpartition = new Userpartition($id_user, $id_partition);
			$userpartition->insert();
			Userpartition::cacheObject($userpartition);
			return $userpartition;
		}
		catch(Excpetion $e){
			throw new Exception("La création de l'objet de type Userpartition a échouée",0,$e);
		}
	}

	public static function get( $id_user_partition){
		$dbh = SingletonPDO::getInstance();
		try{
			if(is_null($id_user_partition) || $id_user_partition === "") {
				return null;
			}
			if(Userpartition::existsInCache($id_user_partition)) {
				return Userpartition::getFromCache($id_user_partition);
			}
			$dbh->beginTransaction();
			$sql= 'SELECT * FROM `userpartition` WHERE `id_user_partition` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$id_user_partition));
			if ($row = $stmt->fetch()){
				$userpartition = new Userpartition( $row['id_user'],$row['id_partition']);
				$userpartition->id =  $row['id_user_partition'];
				$dbh->commit();
				Userpartition::cacheObject($userpartition);
				return $userpartition;
			}
			else {
				$dbh->commit();
				return null;
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récupération de l'objet ayant l'id ". $id_user_partition . " a échouée",0,$e);
		}
	}

	protected function update(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql='UPDATE `userpartition` SET `id_user` = :id_user, `id_partition` = :id_partition WHERE `id_user_partition` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id_user'=>$this->id_user, ':id_partition'=>$this->id_partition, ':id'=>$this->id));
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La modification de l'objet de type ".get_class($this)." ayant l'id ". $this->id . " a échouée",0,$e);
		}
	}

	public function delete(){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			if (is_null($this->id)) {
				throw new Exception("Cet objet de type ".get_class($this)." n'a pas encore été enregistré dans la base");
			}
			$sql = 'DELETE FROM `userpartition` WHERE `id_user_partition` = :id';
			$stmt = $dbh->prepare($sql);
			$stmt->execute(array(':id'=>$this->id));
			Userpartition::removeObjectFromCache($this->id);
			$this->id = null;
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de l'objet de type ".get_class($this)." ayant l'id ". $this->id. " a échouée",0,$e);
		}
	}

	protected function insert(){
		$dbh = SingletonPDO::getInstance();
		try{
			if (is_null($this->id)) {
				$dbh->beginTransaction();
				$sql='INSERT INTO `userpartition` ( `id_user`, `id_partition`) VALUES (:id_user, :id_partition)';
				$stmt = $dbh->prepare($sql);
				$stmt->execute(array(':id_user'=>$this->id_user, ':id_partition'=>$this->id_partition));
				$this->id = $dbh->lastInsertId();
				$dbh->commit();
			}
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("L'insertion de l'objet de type ".get_class($this)." a échouée",0,$e);
		}
	}

	public static function getAll( $search_params = array(),$options = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql = 'SELECT * FROM `userpartition`';
			$sql .= self::generateWhereClause($search_params);
			$sql .= self::generateOptionClause($options);
			$stmt = $dbh->prepare($sql);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$stmt->execute($array);
			while ($row = $stmt->fetch()) {
				$obj = null;
				if(Userpartition::existsInCache($row['id_user_partition'])){
					$obj = Userpartition::getFromCache($row['id_user_partition']);
				}
				else{
					$obj = new Userpartition( $row['id_user'],$row['id_partition']);
				}
				if(!is_null($obj)){
					$obj->id = $row['id_user_partition'];
					Userpartition::cacheObject($obj);
					$objs[] = $obj;
				}
			}
			$dbh->commit();
			return $objs;
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La récuperation de la liste d'objets de type Userpartition a échouée",0,$e);
		}
	}

	public static function deleteAll( $search_params = array()){
		$dbh = SingletonPDO::getInstance();
		try{
			$dbh->beginTransaction();
			$objs = array();
			$sql_delete = 'DELETE FROM `userpartition`';
			$sql_select = 'SELECT id_user_partition FROM `userpartition`';
			$sql_delete .= self::generateWhereClause($search_params);
			$sql_select .= self::generateWhereClause($search_params);
			$stmt_delete = $dbh->prepare($sql_delete);
			$stmt_select = $dbh->prepare($sql_select);
			$array = array();
			$cpt = 0;
			foreach($search_params as $ind => $search_param){
				//ajouter un parametre au tableau
				if($search_param['operator'] === 'BETWEEN' && is_array($search_param['value']) && count($search_param['value']) == 2 ){
					$array[':'.$search_param['field'].$cpt.'_0'] = $search_param['value'][0];
					$array[':'.$search_param['field'].$cpt.'_1'] = $search_param['value'][1];
				}
				else if($search_param['operator'] === 'IN' && is_array($search_param['value']) && count($search_param['value']) > 0){
					$i = 0;
					foreach($search_param['value'] as $key => $val){
						$array[':'.$search_param['field'].$cpt.'_'.$i] = $val;
						$i++;
					}
					if($i == 0){
						throw new Exception("L'opérateur IN doit comporter au moins une valeur");
					}
				}
				else if ($search_param['operator'] === 'IS NULL' || $search_param['operator'] === 'IS NOT NULL'){
					continue;
				}
				else{
					$array[':'.$search_param['field'].$cpt] = $search_param['value'];
				}
				$cpt++;
			}
			$var_select = $stmt_select->execute($array);
			$tab_to_delete_objects = $stmt_select->fetchAll();
			if(sizeof($tab_to_delete_objects) > 0){
				$var_delete = $stmt_delete->execute($array);
				foreach($tab_to_delete_objects as $ind => $row){
					$existing_object = Userpartition::getObjectFromCache($row['id_user_partition']);
					if(!is_null($existing_object)){
						$existing_object->id = null;
						Userpartition::removeObjectFromCache($row['id_user_partition']);
					}
				}
			}
			$dbh->commit();
		}
		catch(Exception $e) {
			$dbh->rollBack();
			throw new Exception("La suppression de la liste d'objets de type Userpartition a échouée",0,$e);
		}
	}

}